package com.hzw.net.net.exception

import android.net.ParseException
import com.google.gson.JsonParseException
import com.google.gson.stream.MalformedJsonException
import com.hzw.net.net.resource.IResource
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import javax.net.ssl.SSLException


/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/4/18 4:29 PM
 *
 * @Description:    APP资源相关异常
 *
 */
class ResourceException : Exception {

    val code: Int

    constructor(errors: Errors, throwable: Throwable? = null): super(errors.msg, throwable) {
        code = errors.code
    }

    constructor(code: Int, message: String, throwable: Throwable? = null): super(message, throwable) {
        this.code = code
    }

    constructor(code: Int, throwable: Throwable? = null): super(throwable) {
        this.code = code
    }

    constructor(resource: IResource<*>, throwable: Throwable? = null) : super(resource.message(), throwable) {
        this.code = resource.code()
    }
}


fun Throwable?.convert(): ResourceException = when (this) {

    is ResourceException -> this //内部有使用, 避免都变成未知错误

    is HttpException -> ResourceException(Errors.HTTP_ERROR, this)

    is JsonParseException -> ResourceException(Errors.PARSE_ERROR, this)

    is JSONException -> ResourceException(Errors.PARSE_ERROR, this)

    is ParseException -> ResourceException(Errors.PARSE_ERROR, this)

    is MalformedJsonException -> ResourceException(Errors.PARSE_ERROR, this)

    is ConnectException -> ResourceException(Errors.NETWORK_ERROR, this)

    is SSLException -> ResourceException(Errors.SSL_ERROR, this)

    is SocketTimeoutException -> ResourceException(Errors.TIMEOUT_ERROR, this)

    is UnknownHostException -> ResourceException(Errors.UNKNOWN_HOST_ERROR, this)

    else -> {
        if (this != null) {
            if (message.isNullOrEmpty()) {
                ResourceException(Errors.UNKNOWN, this)
            } else {
                ResourceException(Errors.UNKNOWN.code, message!!, this)
            }
        } else {
            ResourceException(Errors.UNKNOWN.code, "未知错误")
        }
    }
}